const Topic = require('../models/topics');
const User = require('../models/users');
const HandAccount = require('../models/handAccount');
const path = require('path')
const {baseUrl} = require('../config')

class TopicsCtl {
  async find(ctx) {
    const { per_page = 10 } = ctx.query;
    const page = Math.max(ctx.query.page * 1, 1) - 1;
    const perPage = Math.max(per_page * 1, 1);
    ctx.body = await Topic
      .find({ topicName: new RegExp(ctx.query.q) })
      .limit(perPage).skip(page * perPage);
  }
  async checkTopicExist(ctx, next){
    const topic = await Topic.findById(ctx.params.id);
    if (!topic) { ctx.throw(404, '话题不存在'); }
    await next();
  }
  async findById(ctx) {
    const { fields = '' } = ctx.query;
    const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('');
    const topic = await Topic.findById(ctx.params.id).select(selectFields);
    ctx.body = topic;
  }

  // ! 老的接口 需要上传图片
  // async create(ctx) {
  //   const img = ctx.request.files.img
  //   const basename = path.basename(img.path)
  //   const cover_img = `${baseUrl}/uploads/${basename}`
  //   const {title, introduction} = ctx.request.body
  //   const new_topic = {
  //     cover_img,
  //     title,
  //     introduction
  //   }
  //   const topic = await new Topic(new_topic).save();
  //   ctx.body = topic;
  // }

  // 新的接口 不需要上传图片 直接保存图片
  async create(ctx) {
    const topic = await new Topic(ctx.request.body).save();
    ctx.body = topic;
  }

  async update(ctx) {
    const topic = await Topic.findByIdAndUpdate(ctx.params.id, ctx.request.body);
    ctx.body = topic;
  }
  async listFollowers(ctx) {
    const users = await User.find({ followingTopics: ctx.params.id });
    ctx.body = users;
  }
  async listHandAccounts(ctx) {
    const handAccounts = await HandAccount.find({ topic: ctx.params.id });
    ctx.body = handAccounts;
  }

  async deleteTopic(ctx){
    ctx.body = await Topic.remove({ _id: ctx.params.id })
  }
}

module.exports = new TopicsCtl();